<template>
  <div class="app-container">
    <!--操作按钮-->
    <div style="padding-bottom: 30px;" class="operation_container">
      <ul>
        <li>
          <el-button size="mini" @click="handleCancel">返回</el-button>
        </li>
        <li>
          <el-button size="mini" type="primary" @click="handleSubmit">保存</el-button>
        </li>
      </ul>
    </div>
    <!--折叠面板-->
    <el-collapse v-model="activeNames" @change="handleChange">
      <el-collapse-item name="basicInfo">
        <template slot="title">
          <span>基本信息</span>
          <i class="header-icon el-icon-info" />
        </template>
        <el-form ref="form" :model="data" :rules="rules" :inline="true" size="mini" label-width="125px">
          <el-row :gutter="24" class="form-item-group">
            <el-col :span="6">
              <el-form-item label="SPU编号：">
                <el-input v-model="data.id" disabled />

              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="SPU名称：">
                <el-input v-model="data.spuName" disabled />

              </el-form-item>
            </el-col>
            <el-col :span="6">

              <el-form-item label="品牌名称：">
                <el-input v-model="data.brandName" disabled />

              </el-form-item>

            </el-col>
            <el-col :span="6">
                <el-form-item label="分类：">
                <el-input v-model="data.categoryName" disabled />

              </el-form-item>

            </el-col>
          </el-row>            <el-row :gutter="24" class="form-item-group">
            <el-col :span="6">

              <el-form-item label="序列号：">                  <el-input v-model="data.sn" disabled />

              </el-form-item>

            </el-col>




            <el-col :span="6" width="100">
              <el-form-item label="介绍：" prop="introduction">
                <el-input v-model="data.introduction" />
              </el-form-item>
            </el-col>


          </el-row>




        </el-form>
      </el-collapse-item>
      <el-collapse-item name="itemInfo">
        <template slot="title">
          <span>SKU明细信息</span>
          <i class="header-icon el-icon-info" />
        </template>
        <el-button type="primary" style="margin-top: 6px; margin-bottom: 1px;" size="mini"
          @click="handleItemFormDisplay">填写明细</el-button>
        <el-button v-if="itemDisplay" type="primary" style="margin-top: 6px; margin-bottom: 1px;" size="mini"
          @click="handleItemAdd">添加</el-button>
        <el-card v-if="itemDisplay" class="box-card">
          <el-form ref="itemForm" :model="itemData" :rules="itemRules" :inline="true" size="mini" label-width="125px">
            <el-row :gutter="24" class="form-item-group">
              <el-col :span="6">
                <el-form-item label="sku名称：" prop="skuName">
                  <el-input v-model="itemData.skuName" />

                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="规格：">
                  <el-input v-model="itemData.spec" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                 <el-form-item label="重量：">
                  <el-input v-model="itemData.weight" type="number" />
                 </el-form-item>
              </el-col>

            </el-row>
          </el-form>
        </el-card>
        <el-divider />
        <el-table :data="data.skuList" border stripe fit highlight-current-row>
          <el-table-column align="center" label="序" width="95">
            <template slot-scope="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="sku名称" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.skuName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.spec }}</span>
            </template>
          </el-table-column>
          <el-table-column label="重量" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.weight }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button type="text" @click="handleItemEdit(scope.row)">修改</el-button>
              <el-button type="text" @click="handleItemDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script>
  import appConstant from '@/constant/AppConstant'
  import SpuApi from '@/api/goods/SpuApi'


  export default {

    components: {

    },
    filters: {
      categoryFilter(item) {
        const values = appConstant.categoryList.filter(value => value.key === item)
        if (values && values.length > 0) {
          return values[0].label
        } else {
          return ''
        }
      }
    },
    data() {
      return {
        activeNames: [
          'basicInfo',
          'itemInfo'
        ],
        selects: {

        },
        operation: undefined,
        data: {
          skuList: [],
          id: undefined,
          categoryId: undefined,
          sn: undefined,
          brandName: undefined,
          brandId: undefined,
          spuName: undefined,
          categoryName: undefined,
          introduction: undefined
        },
        // 校验规则的名称必须和校验字段的名称一致
        rules: {
          /*  departureIdList: [{ required: true, message: '_', trigger: 'change' }],
            destinationIdList: [{ required: true, message: '_', trigger: 'change' }] */
        },
        /*  materialSelectorVisible: false,
          fromSelectorVisible: false,
          toSelectorVisible: false,
          orgSelectorVisible: false,
          vehicleModelSelectorVisible: false, */
        itemDisplay: false,
        itemData: {
          spec: undefined,
          skuName: undefined,
          weight: undefined
        },
        itemRules: {
          spec: [{
            required: true,
            message: '_',
            trigger: 'blur'
          }],
          skuName: [{
            required: true,
            message: '_',
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      this.initForm()
      this.loadSelects()
    },
    methods: {
      initForm() {
        const id = this.$route.params.id
        if (id) {

          SpuApi.get(id).then(response => {
            this.data = response.data
            // 将字符串转为数组

          })
        } else {
          this.operation = 'add'
        }
      },
      loadSelects() {
        /*  LocationApi.list().then(response => {
            this.selects.locationList = TreeUtils.list2Tree(response.data)
          }) */
      },
      handleSubmit() {

        // 将数组转为字符串


        SpuApi.addSku(this.data).then(response => {
          this.$message.success('新增sku成功！')
          this.$router.go(-1)
        })


      },
      handleCancel() {
        this.$router.go(-1)
      },
      handleChange(val) {
        console.log(val)
      },
      openMaterialSelector() {
        this.materialSelectorVisible = true
      },
      handleMaterialSelected(obj) {
        this.itemData = {
          ...this.itemData,
          cargoFreightName: obj.materialName,
          cargoFreightType: obj.categoryId,
          unitPrice: obj.unitPrice,
          cargoFreightNo: obj.id,
          settledBasedOn: obj.settledBasedOn,
          shipByPackOrqty: obj.shipBasedOn,
          unitVolume: obj.unitVolume,
          unitWeight: obj.unitWeight,
          packing: obj.packNo,
          weightMeasUnit: obj.weightMeasUnit,
          qtyPerPack: obj.qtyPerPack
        }
        if (obj.specType) {
          if (obj.specType === 'PH') {
            this.itemData.shipByPackOrqty = 'volume'
          }
        }
      },
      openFromSelector() {
        this.fromSelectorVisible = true
      },
      handleFromSelected(obj) {
        this.data.customerNo = obj.id
        this.data.customerName = obj.customerName
        this.data.customerPhone = obj.phone
        this.data.customerAddress = obj.address
        this.data.departure = obj.areaDesc
        if (this.data.departure) {
          this.data.departureIdList = this.data.departure.split(',')
        }
      },
      openToSelector() {
        this.toSelectorVisible = true
      },
      handleToSelected(obj) {
        this.data = {
          ...this.data,
          consigneeName: obj.consigneeName,
          consigneeNo: obj.id,
          consigneePhone: obj.linkManMobile,
          consigneeAddress: obj.consigneeAddress,
          destination: obj.areaDesc
        }
        if (this.data.destination) {
          this.data.destinationIdList = this.data.destination.split(',')
        }
      },
      handleItemFormDisplay() {
        this.itemDisplay = !this.itemDisplay
        this.itemData = {}
      },
      handleItemAdd() {
        if (this.itemData.skuName) {
          // 解决skuList中所有item的内存地址一样的问题
          const data = {
            ...this.itemData
          }
          // 校验必填字段
          this.$refs['itemForm'].validate((valid) => {
            if (valid) {
              this.data.skuList.push(data)
              this.itemData = {
                spec: undefined,
                skuName: undefined,
                weight: undefined

              }
              this.$message.success('添加成功！')
            }
          })
        } else {
          this.$message.warning('请填写sku名称！')
        }
      },
      handleItemEdit(data) {
        this.itemDisplay = true
        this.itemData = {
          ...data
        }
        this.handleItemDelete(data)
      },
      handleItemDelete(data) {
        const index = this.data.skuList.indexOf(data)
        this.data.skuList.splice(index, 1)
      },
      handleCalShipmentExpense() {
        if (this.itemData.countPrice && this.itemData.shipByPackOrqty) {
          if (this.itemData.shipByPackOrqty === 'weight') {
            if (this.itemData.weight) {
              this.itemData.countCarriage = this.itemData.countPrice * this.itemData.weight
            }
          } else if (this.itemData.shipByPackOrqty === 'qty') {
            if (this.itemData.quantity) {
              this.itemData.countCarriage = this.itemData.countPrice * this.itemData.quantity
            }
          } else if (this.itemData.shipByPackOrqty === 'pack') {
            if (this.itemData.packQty) {
              this.itemData.countCarriage = this.itemData.countPrice * this.itemData.packQty
            }
          } else {
            if (this.itemData.volume) {
              this.itemData.countCarriage = this.itemData.countPrice * this.itemData.volume
            }
          }
          this.itemData.amountExpense = this.itemData.countCarriage
        } else {
          this.itemData.countCarriage = 0
        }
      },
      handleCalMaterialValue() {
        if (this.itemData.unitPrice && this.itemData.shipByPackOrqty) {
          if (this.itemData.shipByPackOrqty === 'weight') {
            if (this.itemData.weight) {
              this.itemData.cargoValue = this.itemData.unitPrice * this.itemData.weight
            }
          } else if (this.itemData.shipByPackOrqty === 'qty') {
            if (this.itemData.quantity) {
              this.itemData.cargoValue = this.itemData.unitPrice * this.itemData.quantity
            }
          } else if (this.itemData.shipByPackOrqty === 'pack') {
            if (this.itemData.packQty) {
              this.itemData.cargoValue = this.itemData.unitPrice * this.itemData.packQty
            }
          } else {
            if (this.itemData.volume) {
              this.itemData.cargoValue = this.itemData.unitPrice * this.itemData.volume
            }
          }
          this.handleCalInsuranceExpense()
        } else {
          this.itemData.materialValue = 0
        }
      },
      handleCalInsuranceExpense() {
        if (this.itemData.materialValue && this.itemData.insuranceFeeRate) {
          this.itemData.insuranceExpense = this.itemData.materialValue * this.itemData.insuranceFeeRate
        } else {
          this.itemData.insuranceExpense = 0
        }
      },
      handleLocationChange() {
        // 先清空里程
        this.data.miles = undefined
        if (this.data.departureIdList.length !== 0 && this.data.destinationIdList.length !== 0) {
          // 根据起始地和目的地，查询线路信息
          const params = {
            startLocation: this.data.departureIdList.join(','),
            endLocation: this.data.destinationIdList.join(',')
          }
          TransitRouteApi.list(params).then(response => {
            if (response.data.length > 0) {
              // 设置里程
              this.data.miles = response.data[0].milometer
              this.data.estDeliveryDays = response.data[0].estDeliveryDays
            }
          })
        }
      },
      openVehicleModelSelector() {
        this.vehicleModelSelectorVisible = true
      },
      handleVehicleModelSelected(obj) {
        this.data.vehicleModelNo = obj.id
        this.data.ftlRequestVehicleType = obj.vehicleModelDesc
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
</style>
